package com.ng.finance.api.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ng.finance.api.entity.BxVoucher;
import com.ng.finance.api.entity.UserPay;
import com.ng.finance.api.entity.WechatUser;
import com.ng.finance.api.mapper.UserPayMapper;
import com.ng.finance.api.service.BxVoucherService;
import com.ng.finance.api.service.UserPayService;
import com.ng.finance.api.service.WechatUserService;
import com.ng.finance.api.vo.UserPayVo;
import com.ng.finance.common.constant.ResultCode;
import com.ng.finance.common.constant.UserRoleConstant;
import com.ng.finance.common.pojo.Result;
import com.ng.finance.common.util.ApiTokenUtils;
import com.ng.finance.common.util.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ng.finance.common.util.DateUtils.YMDHMS_BREAK_HALF;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 83673
 * @since 2018-09-14
 */
@Service
public class UserPayServiceImpl extends ServiceImpl<UserPayMapper, UserPay> implements UserPayService {

    @Resource
    WechatUserService wechatUserService;

    @Resource
    UserPayMapper userPayMapper;

    @Resource
    private UserPayService userPayService;

    @Resource
    private ApiTokenUtils apiTokenUtils;

    @Resource
    private BxVoucherService bxVoucherService;


    @Override
    public Result recordPay(UserPayVo userPay) {

        //查询用户是否存在
        EntityWrapper<WechatUser> userEntityWrapper = new EntityWrapper<>();
        String unionId = apiTokenUtils.getUnionId();
        userEntityWrapper.eq(WechatUser.UINIONID, unionId);
        WechatUser wechatUser = wechatUserService.selectOne(userEntityWrapper);
        if (ObjectUtils.isEmpty(wechatUser)) {
            return Result.build(ResultCode.UNAUTHORIZED, "未绑定");
        }

        UserPay userPayVo = new UserPay(userPay.getPayType(), userPay.getPayRemark(), userPay.getPayTime(), userPay.getPayMoney(),
                wechatUser.getId(), wechatUser.getUserName(), wechatUser.getWechatPic(),
                wechatUser.getUserPhone(), wechatUser.getOpenid(), wechatUser.getUnionid(),
                wechatUser.getWechatPic(), wechatUser.getWechatNick(), 0, UserRoleConstant.read_role_2, userPay.getPayPic(), userPay.getAddress(), userPay.getTotalPerson());
        Integer integer = baseMapper.insert(userPayVo);

        return Result.build(integer > 0 ? ResultCode.SUCCESS : ResultCode.FAILED, integer > 0 ? "添加记录成功!" : "添加记录失败");
    }

    @Override
    public Double selectYesterdayPay() {
        return userPayMapper.selectYesterdayPay();
    }

    @Override
    public Double getTotalPay() {
        return userPayMapper.getTotalPay();
    }

    @Override
    public Result alreadyRead(Integer lookState, Long id) {
        Integer integer = userPayMapper.updateById(new UserPay(id, lookState));
        return Result.build(integer > 0 ? ResultCode.SUCCESS : ResultCode.FAILED, integer > 0 ? "操作成功" : "操作失败");
    }


    /**
     * 查詢個人消費列表
     *
     * @param payTime
     * @return
     */
    @Override
    public Result selectPersonPayList(String payTime, Page page) {
        String unionId = apiTokenUtils.getUnionId();
        List<UserPay> userPayList = baseMapper.selectPersonPayList(payTime, unionId, page);
        Double payMonth = baseMapper.selectPersonMonthPay(payTime, unionId);

        if (payMonth == null) {
            payMonth = 0.00;
        }

        Map<String, Object> map = new HashMap<>();
        page.setRecords(userPayList);
        map.put("total", page.getTotal());
        map.put("list", page.getRecords());
        map.put("pages", page.getPages());
        map.put("current", page.getCurrent());
        map.put("payMonth", payMonth);
        return Result.build(ResultCode.SUCCESS, map);
    }

    @Override
    public Map<String, Object> selectMonthPayList(String payTime, Page page) {
        List<UserPay> userPayList = baseMapper.queryUserPayList(payTime, page);
        Map<String, Object> map = new HashMap<>();
        page.setRecords(userPayList);
        map.put("total", page.getTotal());
        map.put("list", page.getRecords());
        map.put("pages", page.getPages());
        map.put("current", page.getCurrent());

        return map;
    }

    @Override
    public Result deleteMyPay(String id) {
        Integer integer = userPayMapper.deleteMyPay(id);
        return Result.build(integer > 0 ? ResultCode.SUCCESS : ResultCode.FAILED, integer > 0 ? "操作成功" : "操作失败");
    }

    @Override
    public Result selectPersonPay() {

        String unionId = apiTokenUtils.getUnionId();
        //查询个人总消费
        Double payTotal = userPayMapper.selectPersonPay(unionId);

        return Result.build(ResultCode.SUCCESS, payTotal);
    }

    @Override
    public Double getMonthTotalPay(String payTime) {
        return userPayMapper.getMonthTotalPay(payTime);
    }

    @Override
    public Double getTodayTotalPay() {
        return userPayMapper.getTodayTotalPay();
    }

    @Override
    public Result updatePay(UserPayVo userPay) {
        //查询消费记录是否存在
        UserPay userPay1 = baseMapper.selectById(userPay.getId());
        if (ObjectUtils.isEmpty(userPay1)) {
            return Result.build(ResultCode.PARAM_ERROR, "消费记录不存在!");
        }
        BeanUtils.copyProperties(userPay, userPay1);
        userPay1.setPayTime(DateUtils.getDate(userPay.getPayTime(), YMDHMS_BREAK_HALF));
        Integer integer = baseMapper.updateById(userPay1);
        return Result.build(integer > 0 ? ResultCode.SUCCESS : ResultCode.FAILED, integer > 0 ? "操作成功" : "操作失败");
    }

    @Override
    public Result selectNoReadList(String userId, Integer payType, Integer lookState, String payTime, Page page) {
        if (StringUtils.isEmpty(userId)) {
            String unionId = apiTokenUtils.getUnionId();
            EntityWrapper<WechatUser> userEntityWrapper = new EntityWrapper<>();
            userEntityWrapper.eq(WechatUser.UINIONID, unionId);
            WechatUser wechatUser = wechatUserService.selectOne(userEntityWrapper);
            if (ObjectUtils.isEmpty(wechatUser)) {
                return Result.build(ResultCode.UNAUTHORIZED, "未绑定");
            }

            if (wechatUser.getRole() == 2) {
                userId = wechatUser.getId() + "";
            }
        }
        Map<String, Object> map = new HashMap<>();
        List<UserPay> userPayList = baseMapper.selectNoReadList(userId, payType, lookState, payTime, page);
        page.setRecords(userPayList);
        map.put("total", page.getTotal());
        map.put("list", page.getRecords());
        map.put("pages", page.getPages());
        map.put("current", page.getCurrent());
        return Result.build(ResultCode.SUCCESS, map);
    }


    @Override
    public Result moreReadByUserId(List<String> ids) {
        List<UserPay> list = new ArrayList<>();
        ids.forEach(p ->
                list.add(new UserPay(p, 1))
        );
        boolean batchById = userPayService.updateBatchById(list);
        return Result.build(batchById ? ResultCode.SUCCESS : ResultCode.FAILED, batchById ? "操作成功" : "操作失败");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result moreUnreimbursed(List<String> ids, List<String> moneys, String time, Long userId, String saveids) {
        //查询报销人是否存在
        EntityWrapper<WechatUser> userEntityWrapper = new EntityWrapper<>();
        userEntityWrapper.eq(WechatUser.ID, userId);
        WechatUser wechatUser = wechatUserService.selectOne(userEntityWrapper);
        if (ObjectUtils.isEmpty(wechatUser)) {
            return Result.build(ResultCode.FORBIDDEN, "报销人不存在");
        }

        List<UserPay> userPayList = ids.parallelStream().map(p -> new UserPay(p, 3)).collect(Collectors.toList());
        boolean b = this.updateBatchById(userPayList);
        //生成报销单
        Double bxMoney = 0d;//报销金额
        for (int i = 0; i < moneys.size(); i++) {
            Double money = Double.valueOf(moneys.get(i));
            bxMoney = bxMoney + money;
        }
        BxVoucher bxVoucher = new BxVoucher(bxMoney, userId, wechatUser.getUserName(), time, saveids);
        boolean insert = bxVoucherService.insert(bxVoucher);
        if (!b || !insert) {
            throw new RuntimeException("操作失败!");
        }
        return Result.build(ResultCode.SUCCESS, bxVoucher.getId());
    }


}
